import requests,asyncio,aiohttp,aiofiles,pytz,os
from util.pf import printf
from pyzbar.pyzbar import decode
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
class Download():
    def __init__(self):
        self.semaphore = asyncio.Semaphore(50)
        self.info = None
        self.Q = None
        self.fail = []
        self.total = None
        self.count = 0
    def updata(self):
        self.count += 1
        printf(f"下载进度{self.count}/{self.total}",end='\r')
    async def main(self,info,QQ):
        self.info = info
        self.Q = QQ
        self.total = len(self.info)
        tasks = []
        for i in self.info:
            tasks.append(self.download(i))
        await asyncio.gather(*tasks)
    def t(self,timestamp): # 时间戳转时间
        dt = datetime.utcfromtimestamp(timestamp)
        beijing_timezone = pytz.timezone('Asia/Shanghai')
        dt_beijing = dt.replace(tzinfo=pytz.utc).astimezone(beijing_timezone)
        return dt_beijing.strftime('%Y-%m-%d %H:%M:%S')
    async def download(self,info,deapth=3):
        if deapth == 0:
            self.fail.append(info)
            return 
        url = info[1]
        name = str(info[0])+"/"+"拍摄时间"+str(self.t(info[2]))+"上传时间"+str(info[3])+str(info[4])
        name = name.replace(" ","_").replace(":","_")
        try:
            async with self.semaphore:
                async with aiohttp.ClientSession(timeout= aiohttp.ClientTimeout(total=60)) as session:
                    async with session.get(url) as r:
                        if r.status == 200:
                            async with aiofiles.open(f"album/{self.Q}/"+name,"wb") as f:
                                await f.write(await r.read())
                            self.updata()
                        else:
                            self.fail.append(info)
        except:
            try:
                os.remove(f"album/{self.Q}/"+name)
            except:
                pass
            await self.download(info,deapth-1)
    def dl(self,info,deapth=3):
        if deapth == 0:
            self.fail.append(info)
            return 
        url = info[1]
        name = str(info[0])+"/"+"拍摄时间"+str(self.t(info[2]))+"上传时间"+str(info[3])+str(info[4])
        name = name.replace(" ","_").replace(":","_")
        try:
            response = requests.get(url,timeout=600)
            if response.status_code == 200:
                with open(f"album/{self.Q}/"+name,"wb") as f:
                    f.write(response.content)
                self.updata()
            else:
                self.fail.append(info)
        except:
            os.remove(f"album/{self.Q}/"+name)
            self.dl(info,deapth-1)
    def thread(self,info,QQ):
        self.count = 0
        self.info = info
        self.Q = QQ
        self.total = len(self.info)
        with ThreadPoolExecutor(max_workers=30) as executor:
            for i in self.info:
                executor.submit(self.dl,i)
